package spring.security.core.support;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Stopwatch;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class LoggingInterceptor implements Interceptor {
	
	private static final Logger logger = LoggerFactory.getLogger(LoggingInterceptor.class);

	public Response intercept(Chain chain) throws IOException {
		Request request = chain.request();
		if (logger.isDebugEnabled()) {
			logger.debug(String.format("发送请求: [%s] %n%s", new Object[] { chain.request(), request.headers() }));
		}

		Stopwatch stopwatch = Stopwatch.createStarted();
		Response response = chain.proceed(request);
		stopwatch.stop();
		ResponseBody responseBody;
		if (logger.isDebugEnabled()) {
			responseBody = response.peekBody(Long.MAX_VALUE);
			logger.debug(String.format("接收响应: [%s] %n返回数据:[%s] %sms%n%s",
					new Object[] { response.request(), responseBody.string(),
							Long.valueOf(stopwatch.elapsed(TimeUnit.MILLISECONDS)), response.headers() }));
		} else if (logger.isInfoEnabled()) {
			responseBody = response.peekBody(50L);
			logger.info("请求:{}, 响应:{}, {}ms", new Object[] { response.request(), responseBody.string() + "...",
					Long.valueOf(stopwatch.elapsed(TimeUnit.MILLISECONDS)) });
		}

		return response;
	}
	
}
